﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;

namespace TBP5283.TSuiteReportingPortal.Business.Extensions.Filters
{
    public class CustomizedFilter : FilterAttribute, IAuthorizationFilter
    {
        public string RedirectUrl { get;set; }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)// this can be your filter rules
            {
                string url = RedirectUrl ?? string.Format("{0}?returnUrl={1}", System.Web.Security.FormsAuthentication.LoginUrl,
                filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl));
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    var redirectResult = filterContext.Result as RedirectResult;
                    if (filterContext.Result is RedirectResult)
                    {
                        // It was a RedirectResult => we need to calculate the url
                        var result = filterContext.Result as RedirectResult;
                        url = UrlHelper.GenerateContentUrl(result.Url, filterContext.HttpContext);
                    }
                    else if (filterContext.Result is RedirectToRouteResult)
                    {
                        // It was a RedirectToRouteResult => we need to calculate
                        // the target url
                        var result = filterContext.Result as RedirectToRouteResult;
                        url = UrlHelper.GenerateUrl(result.RouteName, null, null, result.RouteValues, RouteTable.Routes, filterContext.RequestContext, false);
                    }
                    filterContext.Result = new JsonResult
                    {
                        Data = new { Redirect = url },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    //non-ajax request
                    filterContext.Result = new RedirectResult(url);
                }
            }
        }
    }
}
